import React, { useMemo } from 'react'
import {
  observer,
  FormProvider,
  createSchemaField,
  Field,
} from '@formily/react'
import {
  ArrayItems,
  FormItem,
  Space,
  Input,
  Radio,
  Switch,
  NumberPicker,
  Select,
} from '@formily/antd'
import { DrawerSetter, ValueInput } from '@designable/react-settings-form'
import { createForm, onFieldChange } from '@formily/core'
import { FoldItem } from '@designable/react-settings-form'
import { dataSources } from '@designable/event-system'
import { ExpressionDialogSetter } from '../ExpressionDialogSetter'
export interface IColumnSetterProps {
  value?: any
  onChange?: (value: any) => void
}

const FoldFormItem = () => {
  const requestOptions = Object.keys(dataSources).map((item) => ({
    label: item,
    value: item,
  }))
  return (
    <FoldItem label="自定义渲染表单项">
      <FoldItem.Base>
        <Field
          name="renderFormItem"
          component={[
            Select,
            {
              options: [
                {
                  label: '选择框',
                  value: 'select',
                },
                {
                  label: '日期范围选择器',
                  value: 'rangePicker',
                },
                {
                  label: '品类选择器',
                  value: 'categoryPicker',
                },
              ],
              allowClear: true,
            },
          ]}
          reactions={(field) => {
            const visible = field.query('.search').value()
            field.visible = visible
          }}
        />
      </FoldItem.Base>
      <FoldItem.Extra>
        <Field
          name="initialValueMonth"
          decorator={[
            FormItem,
            {
              label: '默认一个月时间范围',
            },
          ]}
          component={[Switch, {}]}
          reactions={(field) => {
            const type = field.query('.renderFormItem').value()
            field.visible = type === 'rangePicker'
          }}
        />
        <Field
          name="selectRequest"
          decorator={[
            FormItem,
            {
              label: '请求数据',
              tooltip: '优先与请求表达式，选择后表达式不生效',
            },
          ]}
          component={[Select, { options: requestOptions, allowClear: true }]}
          reactions={(field) => {
            const type = field.query('.renderFormItem').value()
            field.visible = type === 'select'
          }}
        />
        <Field
          name="requestExpression"
          decorator={[
            FormItem,
            {
              label: '请求自定义表达式',
            },
          ]}
          component={[ExpressionDialogSetter, {}]}
          reactions={(field) => {
            const type = field.query('.renderFormItem').value()
            field.visible = type === 'select'
          }}
        />
        <Field
          name="rangStartName"
          decorator={[FormItem, { label: '开始字段名' }]}
          component={[Input, {}]}
          reactions={(field) => {
            const type = field.query('.renderFormItem').value()
            field.visible = type === 'rangePicker'
            const dataIndex = field.query('.dataIndex').value()
            field.value = dataIndex + 'Start'
          }}
        />
        <Field
          name="rangEndName"
          decorator={[FormItem, { label: '结束字段名' }]}
          component={[Input, {}]}
          reactions={(field) => {
            const type = field.query('.renderFormItem').value()
            field.visible = type === 'rangePicker'
            const dataIndex = field.query('.dataIndex').value()
            field.value = dataIndex + 'End'
          }}
        />
      </FoldItem.Extra>
    </FoldItem>
  )
}

const SchemaField = createSchemaField({
  components: {
    ArrayItems,
    Input,
    Space,
    FormItem,
    DrawerSetter,
    Radio,
    Switch,
    NumberPicker,
    ValueInput,
    Select,
    FoldFormItem,
    ExpressionDialogSetter,
  },
})

export const ColumnSetter: React.FC<IColumnSetterProps> = observer((props) => {
  const form = useMemo(
    () =>
      createForm({
        initialValues: props.value,
        effects: (form) => {
          onFieldChange('*', () => {
            props.onChange?.(form.getState().values)
          })
        },
      }),
    []
  )
  return (
    <FormProvider form={form}>
      <SchemaField>
        <SchemaField.Array
          name="data"
          x-component="ArrayItems"
          x-component-props={{
            style: { background: '#eee', marginBottom: 10, padding: 10 },
          }}
        >
          <SchemaField.Object>
            <SchemaField.Void
              x-component="Space"
              x-component-props={{
                style: {
                  background: '#fff',
                  padding: 6,
                  marginBottom: 10,
                },
              }}
            >
              <SchemaField.Void x-component="ArrayItems.SortHandle" />
              <SchemaField.String
                x-decorator="FormItem"
                x-decorator-props={{
                  style: { padding: 0, margin: 0 },
                }}
                required
                name="title"
                x-component="Input"
                x-component-props={{
                  placeholder: '列标题',
                }}
              />
              <SchemaField.Void
                x-component="DrawerSetter"
                x-component-props={{
                  text: '编辑',
                  triggerProps: {
                    style: {
                      height: 30,
                    },
                  },
                }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '列标题',
                  }}
                  required
                  name="title"
                  x-component="Input"
                />
                <SchemaField.String
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '数据字段',
                  }}
                  required
                  name="dataIndex"
                  x-component="Input.TextArea"
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '是否脱敏',
                  }}
                  name="desensitize"
                  x-component="Switch"
                />
                <SchemaField.String
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '提示信息',
                  }}
                  name="tooltip"
                  x-component="Input"
                />
                <SchemaField.Number
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '宽度',
                  }}
                  name="width"
                  x-component="NumberPicker"
                  x-component-props={{
                    addonAfter: 'px',
                    min: 0,
                  }}
                />
                <SchemaField.String
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '列是否固定',
                  }}
                  name="fixed"
                  x-component="Radio.Group"
                  x-component-props={{
                    optionType: 'button',
                    options: [
                      {
                        label: 'left',
                        value: 'left',
                      },
                      {
                        label: 'center',
                        value: '',
                      },
                      {
                        label: 'right',
                        value: 'right',
                      },
                    ],
                  }}
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '标签渲染',
                  }}
                  name="tag"
                  x-component="Switch"
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '隐藏列',
                  }}
                  name="hideInTable"
                  x-component="Switch"
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '超出省略',
                  }}
                  name="ellipsis"
                  x-component="Switch"
                  x-component-props={{
                    defaultChecked: true,
                  }}
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '自定义渲染',
                  }}
                  name="isRender"
                  x-component="Switch"
                />
                <SchemaField.String
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '渲染表达式',
                  }}
                  name="render"
                  x-component="ExpressionDialogSetter"
                  x-reactions={{
                    dependencies: ['.isRender'],
                    fulfill: {
                      state: {
                        visible: '{{!!$deps[0]}}',
                      },
                    },
                  }}
                />
                <SchemaField.Boolean
                  x-decorator="FormItem"
                  x-decorator-props={{
                    label: '列搜索',
                  }}
                  name="search"
                  x-component="Switch"
                />
                <SchemaField.Void
                  x-component="FoldFormItem"
                  x-reactions={{
                    dependencies: ['.search'],
                    // fulfill: {
                    //   state: {
                    //     hidden: '{{!$deps[0]}}',
                    //   },
                    // },
                  }}
                />
              </SchemaField.Void>
              <SchemaField.Void x-component="ArrayItems.Remove" />
            </SchemaField.Void>
          </SchemaField.Object>

          <SchemaField.Void x-component="ArrayItems.Addition" title="添加列" />
        </SchemaField.Array>
      </SchemaField>
    </FormProvider>
  )
})
